import {Component, OnInit, ViewChild} from '@angular/core';
import {BaseGridComponent, BaseService} from '@sb/base';
import {SFSchema} from '@delon/form';
import {NzMessageService, NzModalService, NzTabChangeEvent} from 'ng-zorro-antd';
import {SysConfigSearchForm} from '../entity/sys-config-search-form';
import {STColumn} from '@delon/abc';
import {SysConfig} from '../entity/sys-config';
import {BaseTreeService} from '@sb/base/core/service/base-tree.service';
import {SysConfigService} from '../service/sys-config.service';
import {SysConfigTreeNode} from '../entity/sys-config-tree-node';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {DomSanitizer} from '@angular/platform-browser';
import {SysConfigTreePanelComponent} from '../sys-config-tree-panel/sys-config-tree-panel.component';
import {NzTreeNode} from 'ng-zorro-antd/core/tree/nz-tree-base-node';
import {SysParamSelectSelectConfig} from '../../sys-param/sys-param-tree-select-alain/sys-param-tree-select-alain.component';
import {SysConfigPageTreeSelectAlainSchema} from '../sys-config-page-tree-select-alain/sys-config-page-tree-select-alain.component';
import {SFItemComponent} from '@delon/form/src/sf-item.component';
import {SFComponent} from '@delon/form/src/sf.component';
import {SysParamService} from '../../sys-param/service/sys-param.service';
import {
    SysCodeCategorySelectAlainComponent,
    SysCodeCategorySelectAlainSchema
} from '../../sys-code/sys-code-category-select-alain/sys-code-category-select-alain.component';


@Component({
    selector: 'sys-config',
    templateUrl: './sys-config.component.html',
    styleUrls: ['./sys-config.component.less'],
    providers: [
        {
            provide: BaseTreeService,
            useClass: SysConfigService
        },
        {
            provide: BaseService,
            useClass: SysConfigService
        }
    ]
})
export class SysConfigComponent implements OnInit {

    typeIcon = {
        PAGE: 'dr:hy-application',
        CATEGORY: 'dr:hy-module',
        ITEM: 'dr:hy-menu',
        FIELD_SET: 'dr:hy-menu'
    };

    baseParam: SysConfig = {};

    searchForm: SysConfigSearchForm = {
        parentId: '-1'
    };

    @ViewChild(BaseGridComponent, {static: false})
    baseGrid: BaseGridComponent;

    @ViewChild(SysConfigTreePanelComponent, {static: true})
    sysConfigTreePanelComponent: SysConfigTreePanelComponent;
    schema: SFSchema = {
        properties: {
            name: {
                type: 'string',
                title: '名称',
                minLength: 2
            },
            code: {
                type: 'string',
                title: '编码',
                ui: {
                    visibleIf: {
                        type: ['PAGE']
                    }
                }
            },
            type: {
                type: 'string',
                title: '类型',
                enum: [
                    {
                        value: 'PAGE',
                        label: '分页'
                    },
                    {
                        value: 'CATEGORY',
                        label: '分项'
                    },
                    {
                        value: 'FIELD_SET',
                        label: '分类'
                    },
                    {
                        value: 'ITEM',
                        label: '配置项'
                    }],
                readOnly: true,
            },
            marginLeft: {
                type: 'string',
                title: '左边距（带%）',
                ui: {
                    visibleIf: {
                        type: ['FIELD_SET']
                    }
                }
            },
            paramId: {
                type: 'string',
                title: '数据项来源',
                ui: {
                    widget: 'sys-param-tree-select-alain',
                    visibleIf: {
                        type: ['ITEM']
                    },
                    valueChange: (value: string, sfItemComp: SFItemComponent, sfComp: SFComponent) => {
                        this.sysParamService.getNodeType(value).subscribe(returnForm => {
                            switch (returnForm.message) {
                                case 'TEXT':
                                    sfComp.setValue('/display', 'text');
                                    break;
                                case 'NUMBER':
                                    sfComp.setValue('/display', 'number');
                                    break;
                                case 'BOOLEAN':
                                    sfComp.setValue('/display', 'boolean');
                                    break;
                                case 'SYS_CODE':
                                    sfComp.setValue('/display', 'syscode');
                                    this.sysParamService.getSysCodeModuleCode(value).subscribe(returnForm2 => {
                                        sfComp.setValue('/sysCodeModuleCode', returnForm2.message);
                                    });
                                    break;
                                case 'ATTACHMENT':
                                    sfComp.setValue('/display', 'file');
                                    break;
                            }
                        });
                    }
                } as SysParamSelectSelectConfig
            },
            display: {
                type: 'string',
                title: '展示方式',
                enum: [{
                    label: '开关',
                    value: 'boolean'
                }, {
                    label: '数字输入框',
                    value: 'number'
                }, {
                    label: '单行文本框',
                    value: 'text'
                }, {
                    label: '多行文本框',
                    value: 'textarea'
                }, {
                    label: '下拉框',
                    value: 'select'
                }, {
                    label: '字典选择框',
                    value: 'syscode'
                }, {
                    label: '文件选择框',
                    value: 'file'
                }],
                ui: {
                    widget: 'select',
                    visibleIf: {
                        type: ['ITEM']
                    }
                }
            },
            minRows: {
                type: 'number',
                title: '最小行数',
                ui: {
                    visibleIf: {
                        display: ['textarea']
                    }
                }
            },
            maxRows: {
                type: 'number',
                title: '最大行数',
                ui: {
                    visibleIf: {
                        display: ['textarea']
                    }
                }
            },
            sysCodeModuleCode: {
                type: 'string',
                title: '字典模块',
                ui: {
                    widget: SysCodeCategorySelectAlainComponent.KEY,
                    multiple: false,
                    visibleIf: {
                        display: ['syscode']
                    },
                } as SysCodeCategorySelectAlainSchema,
                readOnly: true,
                description: '如果字典模块有误，请在系统参数中修改！'
            },
            // paramValueAttachment: {
            //     type: 'string',
            //     title: '附件',
            //     ui: {
            //         widget: SysAttachmentUploadAlainComponent.KEY,
            //         multiple: false,
            //         visibleIf: {
            //             display: ['syscode']
            //         },
            //     } as SysAttachmentUploadSchema,
            // },
            // paramValueSysCode: {
            //     type: 'string',
            //     title: '字典项',
            //     ui: {
            // widget: SysCodeTreeSelectAlainComponent.KEY,
            //         multiple: false,
            //         visibleIf: {
            //             valueType: ['SYS_CODE']
            //         },
            //     } as SysCodeTreeSelectAlainSchema,
            // },
            description: {
                type: 'string',
                title: '提示',
                ui: {
                    visibleIf: {
                        type: ['ITEM']
                    }
                }
            },
            visibleType: {
                type: 'string',
                title: '显示方式',
                enum: [{
                    label: '一直显示',
                    value: 'always'
                }, {
                    label: '当指定组件等于',
                    value: 'visibleIf'
                }],
                ui: {
                    widget: 'select',
                    visibleIf: {
                        type: ['ITEM']
                    }
                },
                default: 'always'
            },
            visibleByElement: {
                type: 'string',
                title: '条件组件',
                ui: {
                    widget: 'sys-config-page-tree-select-alain',
                    visibleIf: {
                        visibleType: ['visibleIf']
                    },
                    pageId: ''
                } as SysConfigPageTreeSelectAlainSchema
            },
            visibleByValue: {
                type: 'string',
                title: '条件组件对应值',
                ui: {
                    visibleIf: {
                        visibleType: ['visibleIf']
                    }
                }
            }
        },
        required: ['name', 'type', 'code', 'paramId']
    } as SFSchema;

    activateNzTreeNode: NzTreeNode;
    activateTreeNode: SysConfigTreeNode;
    columns: STColumn[] = [
        {
            title: '',
            type: 'checkbox',
            index: 'id',
            width: '7%',
            className: 'text-center word-wrap'
        }, {
            title: '名称',
            index: 'name',
            width: '15%',
            className: 'text-center word-wrap'
        }, {
            title: '编码',
            index: 'code',
            width: '15%',
            className: 'text-center word-wrap'
        }, {
            title: '类型',
            index: 'type',
            format: v => {
                if (v.type === 'PAGE') {
                    return '页面';
                } else if (v.type === 'CATEGORY') {
                    return '分项';
                } else if (v.type === 'FIELD_SET') {
                    return '分类';
                } else if (v.type === 'ITEM') {
                    return '配置项';
                } else {
                    return '目录';
                }
            },
            width: '15%',
            className: 'text-center word-wrap'
        }, {
            title: '操作区',
            className: 'text-center word-wrap',
            width: '18%',
            buttons: []
        }
    ] as STColumn[];
    tabIndex = 0;
    showPageTab: boolean;
    showCategoryTab: boolean;
    showConfigTab: boolean;
    showDetailTab: boolean;
    showSchemaTab: boolean;

    showGrid = false;
    showDetail = false;
    showSchema = false;

    schemaText: string;


    searchConfig: { [key: string]: any } = {
        searchPermission: false
    };
    settingOptions = [
        {label: '显示权限', value: 'permission'}
    ];

    constructor(
        private message: NzMessageService,
        private sysConfigService: SysConfigService,
        private sysParamService: SysParamService,
        private sanitizer: DomSanitizer,
        private modal: NzModalService) {
    }

    ngOnInit(): void {
    }

    selectNode(nzTreeNode: NzTreeNode): void {
        const treeNode = nzTreeNode.origin as SysConfigTreeNode;
        // 修改 tab显示
        let title = '';
        let change = true;
        if (this.activateTreeNode && this.activateTreeNode.type === treeNode.type) {
            change = false;
        }
        if (change) {
            if (treeNode.type === 'root') {
                this.showPageTab = true;
                this.showCategoryTab = false;
                this.showDetailTab = false;
                this.showConfigTab = false;
                this.showSchemaTab = false;
                title = '页面';
            } else if (treeNode.type === 'PAGE') {
                this.showPageTab = false;
                this.showCategoryTab = true;
                this.showDetailTab = true;
                this.showConfigTab = false;
                this.showSchemaTab = true;
                title = '分项';
            } else if (treeNode.type === 'CATEGORY') {
                this.showPageTab = false;
                this.showCategoryTab = false;
                this.showDetailTab = true;
                this.showConfigTab = true;
                this.showSchemaTab = false;
                title = '分类 / 配置项';
            } else if (treeNode.type === 'FIELD_SET' || treeNode.type === 'ITEM') {
                this.showPageTab = false;
                this.showCategoryTab = false;
                this.showDetailTab = true;
                this.showConfigTab = false;
                this.showSchemaTab = false;
                title = '详情';
            }
            this.tabIndex = 0;
        }

        this.activateTreeNode = treeNode;

        this.activateNzTreeNode = nzTreeNode;

        this.searchForm.parentId = treeNode.key;

        this.reloadGrid(title);
    }

    onDataReload() {
        this.sysConfigTreePanelComponent.reloadNode(this.activateNzTreeNode.key);
    }

    recordWrapper(rmMenu: SysConfig): SysConfig {
        if (this.activateTreeNode.key !== rmMenu.id) {
            Object.assign(rmMenu, {parentId: this.activateTreeNode.key});
        }
        delete rmMenu.iconData;
        return rmMenu;
    }

    beforeRemove(menus: SysConfig[]): Observable<boolean> {
        const subject = new BehaviorSubject(false);
        for (let i = 0; i < menus.length; i++) {
            const menu = menus[i];
            if (menu.type === 'PAGE' || menu.type === 'CATEGORY') {
                this.modal.confirm({
                    nzTitle: '删除提示',
                    nzContent: '删除应用或目录会同时删除当前节点下的所有菜单，是否确定删除?',
                    nzOnOk: () => {
                        subject.next(true);
                        subject.complete();
                    }
                }, 'warning');
                break;
            }

            if (i === menus.length - 1) {
                return of(true);
            }
        }
        return subject;
    }

    itemClick(menu: SysConfig) {
        this.sysConfigTreePanelComponent.triggerClick(menu.id);
    }

    getSvgHtml(picture: string) {
        return this.sanitizer.bypassSecurityTrustHtml(picture);
    }

    nzSelectChange(changeEvent: NzTabChangeEvent) {
        const title = changeEvent.tab.nzTitle as string;
        this.reloadGrid(title);
    }

    reloadGrid(title: string) {
        if (!title) {
            return;
        }
        this.showGrid = false;
        this.showDetail = false;
        this.showSchema = false;
        if (title === '详情') {
            this.updateDetailSchema();
            this.showDetail = true;
        } else if (title === '查看Schema') {
            this.showSchema = true;
        } else {
            this.showGrid = true;
            if (title === '页面') {
                this.baseParam.type = 'PAGE';
            } else if (title === '分项') {
                this.baseParam.type = 'CATEGORY';
            } else if (title === '分类 / 配置项') {
                this.baseParam.type = undefined;
            }
            this.updateGridSchema();
            if (this.baseGrid) {
                this.baseGrid.baseParam = this.baseParam;
                if (this.baseGrid.showType === 'table' && this.baseGrid.st) {
                    this.baseGrid.st.clear();
                    this.baseGrid.st.resetColumns({emitReload: false}).then();
                }
                this.baseGrid.reload();
            }
        }
    }

    updateGridSchema(): void {
        let readOnly = false;
        if (this.activateTreeNode.type === 'root') {
            readOnly = true;
            this.schema.properties.type.enum = [
                {
                    value: 'PAGE',
                    label: '分页'
                }];
        } else if (this.activateTreeNode.type === 'PAGE') {
            this.schema.properties.type.default = 'CATEGORY';
            this.schema.properties.type.enum = [
                {
                    value: 'CATEGORY',
                    label: '分项'
                }];
            readOnly = true;
        } else if (this.activateTreeNode.type === 'CATEGORY') {
            this.schema.properties.type.default = 'ITEM';
            this.schema.properties.type.enum = [
                {
                    value: 'FIELD_SET',
                    label: '分类'
                }, {
                    value: 'ITEM',
                    label: '配置项'
                }
            ];
            readOnly = false;
        }
        let node = this.activateNzTreeNode;
        while (true) {
            if (!node) {
                const temp: SysConfigPageTreeSelectAlainSchema = this.schema.properties.visibleByElement.ui as SysConfigPageTreeSelectAlainSchema;
                temp.pageId = '';
                temp.ignoreId = '';
                break;
            }
            if (node.origin.type === 'PAGE') {
                const temp: SysConfigPageTreeSelectAlainSchema = this.schema.properties.visibleByElement.ui as SysConfigPageTreeSelectAlainSchema;
                temp.pageId = node.key;
                temp.ignoreId = '';
                break;
            } else {
                node = node.parentNode;
            }
        }

        this.schema.properties.type.readOnly = readOnly;
    }

    updateDetailSchema(): void {
        this.schema.properties.type.readOnly = true;
        this.schema.properties.type.enum = [
            {
                value: 'PAGE',
                label: '分页'
            }, {
                value: 'CATEGORY',
                label: '分项'
            }, {
                value: 'FIELD_SET',
                label: '分类'
            }, {
                value: 'ITEM',
                label: '配置项'
            }
        ];


        let node = this.activateNzTreeNode;
        while (true) {
            if (!node) {
                const temp: SysConfigPageTreeSelectAlainSchema = this.schema.properties.visibleByElement.ui as SysConfigPageTreeSelectAlainSchema;
                temp.pageId = '';
                temp.ignoreId = '';
                break;
            }
            if (node.origin.type === 'PAGE') {
                const temp: SysConfigPageTreeSelectAlainSchema = this.schema.properties.visibleByElement.ui as SysConfigPageTreeSelectAlainSchema;
                temp.pageId = node.key;
                temp.ignoreId = this.activateTreeNode.key;
                break;
            } else {
                node = node.parentNode;
            }
        }
    }

    detailClose($event: boolean) {
        const nodeId = this.activateTreeNode.key;
        this.sysConfigTreePanelComponent.reloadNode(this.activateNzTreeNode.parentNode.key).subscribe(() => {
            this.sysConfigTreePanelComponent.triggerClick(nodeId);
        });
    }

    generateSchema() {
        this.sysConfigService.generateSchema(this.activateTreeNode.key).subscribe(returnForm => {
            this.schemaText = JSON.stringify(returnForm.message, null, 4);
        });
    }

    uploadSchema() {
        this.sysConfigService.uploadSchema(this.activateTreeNode.key, this.schemaText).subscribe(() => {
            this.message.info('更新成功！');
        });
    }

}
